package com.chookss.home.audit.reimbursement;

import android.app.Activity;
import android.content.Context;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.viewholder.BaseViewHolder;
import com.chookss.MyApp;
import com.chookss.R;
import com.chookss.Urls;
import com.chookss.base.BaseViewHolderEx;
import com.chookss.home.entity.FileEntity;
import com.chookss.home.entity.FolderEntity;
import com.chookss.tools.MyEvent;
import com.chookss.tools.MyToast;
import com.chookss.tools.SignUtils2;
import com.chookss.tools.Utils;
import com.chookss.tools.okgoconfig.MyHttpRequest;
import com.chookss.tools.okgoconfig.callback.ObserverCallback;
import com.chookss.tools.okgoconfig.model.LzyResponse;
import com.google.gson.reflect.TypeToken;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.lvgroup.hospital.base.BaseAct;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.jetbrains.annotations.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.functions.Consumer;

//报销类型选择
public class ReimbursementTypesActivity extends BaseAct {

    public Context mContext;
    @BindView(R.id.topFlowLayout)
    RecyclerView titleRcv;
    @BindView(R.id.llLine2)
    View llLine2;
    @BindView(R.id.tvTitle)
    TextView tvTitle;
    @BindView(R.id.folderRcv)
    RecyclerView folderRcv;
    @BindView(R.id.srlView)
    SmartRefreshLayout srlView;
    @BindView(R.id.tvFolderName)
    TextView tvFolderName;
    @BindView(R.id.ivFolderArrow)
    ImageView ivFolderArrow;
    @BindView(R.id.llFolderArrow)
    LinearLayout llFolderArrow;
    @BindView(R.id.llFolder)
    LinearLayout llFolder;
    @BindView(R.id.tvFolderTopName)
    TextView tvFolderTopName;
    @BindView(R.id.llFolderTop)
    LinearLayout llFolderTop;
    @BindView(R.id.llFolderAll)
    LinearLayout llFolderAll;
    @BindView(R.id.tvFileName)
    TextView tvFileName;
    @BindView(R.id.ivFileArrow)
    ImageView ivFileArrow;
    @BindView(R.id.llFileArrow)
    LinearLayout llFileArrow;
    @BindView(R.id.llFile)
    LinearLayout llFile;
    @BindView(R.id.tvFileTopName)
    TextView tvFileTopName;
    @BindView(R.id.llFileTop)
    LinearLayout llFileTop;
    @BindView(R.id.llFileAll)
    LinearLayout llFileAll;
    @BindView(R.id.llNone)
    LinearLayout llNone;
    @BindView(R.id.fileRcv)
    RecyclerView fileRcv;
    @BindView(R.id.tvFileArrow)
    TextView tvFileArrow;
    @BindView(R.id.tvFolderArrow)
    TextView tvFolderArrow;
    @BindView(R.id.spaceView)
    View spaceView;

    private int currentPage = 1;
    private String pageSize = "50";
    private boolean isEnd = false;//是否到底
    //文件夹
    private List<FolderEntity> folderList = new ArrayList<>();
    private ReimbursementFolderAdapter folderAdapter;
    //文件
    private ReimbursementTypeAdapter fileListAdapter;
    private List<FileEntity> fileList = new ArrayList<>();
    //目录
    private TitleAdapter titleAdapter;
    private ArrayList<String> nameList = new ArrayList<>();//组织排列
    private int level = 0;//默认层级
    private String parentCode = "";//上层级传下来的
    private boolean folderOpen = false, fileOpen = false;//默认都是关闭状态

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_reimbursement_types);
        ButterKnife.bind(this);
        mContext = this;
        initState();

    }

    @Override
    public void initData() {
        level = getIntent().getIntExtra("level", 0);
        ArrayList<String> nameLists = getIntent().getStringArrayListExtra("nameList");
        if (nameLists != null) {
            nameList.addAll(nameLists);
        }
        if (nameList.size() > 1) {
            tvTitle.setText(nameList.get(nameList.size() - 1));
            titleAdapter = new TitleAdapter(R.layout.item_folder_name_list, this, nameList);
            LinearLayoutManager lm = new LinearLayoutManager(this);
            lm.setOrientation(LinearLayoutManager.HORIZONTAL);
            titleRcv.setLayoutManager(lm);
            titleRcv.setAdapter(titleAdapter);
            titleRcv.setVisibility(View.VISIBLE);
            llLine2.setVisibility(View.VISIBLE);
        } else {
            if (nameList.size() == 1) {
                tvTitle.setText(nameList.get(0));
            } else {
                tvTitle.setText("报销类型");
            }
        }
        parentCode = getIntent().getStringExtra("parentCode");
        srlView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                if (isEnd) {//has next page
                    MyToast.show("没有更多数据了");
                    loadEnd();
                } else {
                    currentPage++;
                    getFileList();
                }
            }
        });
        srlView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshLayout) {
                currentPage = 1;
                isEnd = false;
                getCatalogData();
                //定时器 倒计时
                Observable.timer(200, TimeUnit.MILLISECONDS).observeOn(AndroidSchedulers.mainThread())
                        .subscribe(new Consumer<Long>() {
                            @Override
                            public void accept(Long aLong) {
                                getFileList();
                            }
                        });
            }
        });
        //文件夹
        folderRcv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        folderAdapter = new ReimbursementFolderAdapter(R.layout.item_reimbursement_folder, this, folderList, nameList, level);
        folderRcv.setAdapter(folderAdapter);
        //文件
        fileRcv.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.VERTICAL, false));
        fileListAdapter = new ReimbursementTypeAdapter(R.layout.item_reimbursement_type, this, fileList);
        fileRcv.setAdapter(fileListAdapter);
        srlView.autoRefresh();
    }

    private void getCatalogData() {
        Map<String, String> map = new HashMap<>();
        if (!Utils.isNull(parentCode)) {
            map.put("baoxiaoTypeCatalogCode", parentCode);
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<FolderEntity>>>() {
        }.getType(), null, Urls.selectAppBaoxiaoTypeCatalogTree, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<FolderEntity>>() {
            @Override
            public void onSuccess(List<FolderEntity> data) {
                loadEnd();
                folderList.clear();
                folderAdapter.notifyDataSetChanged();
                if (data != null && data.size() > 0) {
                    folderList.addAll(data);
                    folderAdapter.notifyDataSetChanged();
                }
                llFolderTop.setVisibility(View.GONE);
                folderOpen = false;
                tvFolderArrow.setVisibility(View.INVISIBLE);
                ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                if (folderList.size() == 0) {
                    folderRcv.setVisibility(View.GONE);
                    llFolderAll.setVisibility(View.GONE);
                    spaceView.setVisibility(View.GONE);
                } else {
                    folderRcv.setVisibility(View.VISIBLE);
                    llFolderAll.setVisibility(View.VISIBLE);
                    llNone.setVisibility(View.GONE);
                    if (fileList.size() > 0) {
                        spaceView.setVisibility(View.VISIBLE);
                    } else {
                        spaceView.setVisibility(View.GONE);
                    }
                }
                if (folderList.size() > 0) {
                    tvFolderTopName.setText("共" + folderList.size() + "个科目");
                    tvFolderName.setText("科目");
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void getFileList() {
        Map<String, String> map = new HashMap<>();
        map.put("pageNum", currentPage + "");
        map.put("pageSize", pageSize + "");
        if (!Utils.isNull(parentCode)) {
            map.put("baoxiaoTypeCatalogCode", parentCode);
        }
        MyHttpRequest.getDefault().getRequest(new TypeToken<LzyResponse<List<FileEntity>>>() {
        }.getType(), null, Urls.selectAppBaoxiaoByCatalog, SignUtils2.makeSignStr(map), false, new ObserverCallback<List<FileEntity>>() {
            @Override
            public void onSuccess(List<FileEntity> data) {
                loadEnd();
                if (currentPage == 1) {
                    fileList.clear();
                    fileListAdapter.notifyDataSetChanged();
                }
                llFileTop.setVisibility(View.GONE);
                fileOpen = false;
                tvFileArrow.setVisibility(View.INVISIBLE);
                ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                if (data != null && data.size() > 0) {
                    fileList.addAll(data);
                    fileListAdapter.notifyDataSetChanged();
                    fileRcv.setVisibility(View.VISIBLE);
                    llFileAll.setVisibility(View.VISIBLE);
                    if (folderList.size() > 0) {
                        spaceView.setVisibility(View.VISIBLE);
                    } else {
                        spaceView.setVisibility(View.GONE);
                    }
                    llNone.setVisibility(View.GONE);
                } else {
                    isEnd = true;
                    if (fileList.size() == 0) {
                        spaceView.setVisibility(View.GONE);
                        fileRcv.setVisibility(View.GONE);
                        llFileAll.setVisibility(View.GONE);
                        if (folderList.size() == 0) {
                            llNone.setVisibility(View.VISIBLE);
                        } else {
                            llNone.setVisibility(View.GONE);
                        }
                    } else {
                        if (folderList.size() > 0) {
                            spaceView.setVisibility(View.VISIBLE);
                        } else {
                            spaceView.setVisibility(View.GONE);
                        }
                        fileRcv.setVisibility(View.VISIBLE);
                        llFileAll.setVisibility(View.VISIBLE);
                        llNone.setVisibility(View.GONE);
                    }
                }
                if (fileList.size() > 0) {
                    tvFileTopName.setText("共" + fileList.size() + "个报销类型");
                }
            }

            @Override
            public void onError(String errorMsg) {
                loadEnd();
                MyToast.show(Utils.onErrorTips(errorMsg));
            }
        });
    }

    private void loadEnd() {
        if (null != srlView && srlView.getState() == RefreshState.Refreshing)
            srlView.finishRefresh();
        if (null != srlView && srlView.getState() == RefreshState.Loading)
            srlView.finishLoadMore();
    }

    class TitleAdapter extends BaseQuickAdapter<String, BaseViewHolderEx> {
        private Activity context;

        public TitleAdapter(int layoutResId, Activity context, @io.reactivex.annotations.Nullable List<String> data) {
            super(layoutResId, data);
            this.context = context;
        }

        @Override
        protected void convert(BaseViewHolderEx helper, String entity) {
            TextView tvItemTitle = helper.getView(R.id.tvTitle);
            ImageView ivArrow = helper.getView(R.id.ivArrow);
            tvItemTitle.setText(entity);
            if (helper.getItemPosition() > 0) {
                ivArrow.setVisibility(View.VISIBLE);
            } else {
                ivArrow.setVisibility(View.GONE);
            }
            if (helper.getItemPosition() == nameList.size() - 1) {
                tvItemTitle.setTextColor(Color.parseColor("#333333"));
            } else {
                tvItemTitle.setTextColor(Color.parseColor("#8a8a8a"));
            }
            helper.getItemView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (Urls.antiShake.check()) {
                        return;
                    }
                    HashMap<String, String> map = new HashMap<>();
                    map.put("ReimbursementTypesActivity", (helper.getItemPosition() + 1) + "");
                    KLog.i((helper.getItemPosition() + 1) + "==");
                    EventBus.getDefault().post(new MyEvent(map));
                }
            });
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MyEvent messageEvent) {
        //事件订阅者处理事件
        if (messageEvent.getHashMap() != null) {
            HashMap<String, String> map = messageEvent.getHashMap();
            if (map.containsKey("ReimbursementTypesActivity")) {
                int oldLevel;
                try {
                    oldLevel = Integer.parseInt(map.get("ReimbursementTypesActivity"));
                } catch (NumberFormatException e) {
                    e.printStackTrace();
                    oldLevel=0;
                }
                if (level > oldLevel) {
                    KLog.i(level + "==" + oldLevel);
                    finish();
                }
            } else if (map.containsKey("clear_baoixaoTypeCode")) {
                String code = map.get("clear_baoixaoTypeCode");
                for (int i = 0; i < fileList.size(); i++) {
                    if (code.equals(fileList.get(i).getBaoixaoTypeCode())) {
                        fileList.get(i).setSelect(false);
                        fileListAdapter.notifyItemChanged(i);
                    }
                }
            }
        }
    }

    @OnClick({R.id.title_back, R.id.common_right_txt, R.id.llFileArrow, R.id.llFolderArrow, R.id.llFolderTop, R.id.llFileTop})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.common_right_txt:
                if(MyApp.fileEntity==null){
                    MyToast.show("请先选择报销类型");
                }else{
                    Map<String, String> map = new HashMap<>();
                    map.put("select_baoixaoTypeCode", MyApp.fileEntity.getBaoixaoTypeCode());
                    map.put("select_baoixaoTypeName", MyApp.fileEntity.getBaoixaoTypeName());
                    map.put("select_baoixaoTypeRemark", MyApp.fileEntity.getRemark());
                    EventBus.getDefault().post(new MyEvent(map));
                    HashMap<String, String> finishMap = new HashMap<>();
                    finishMap.put("ReimbursementTypesActivity", -1 + "");
                    EventBus.getDefault().post(new MyEvent(finishMap));
                }
                break;
            case R.id.llFolderArrow:
            case R.id.llFolderTop:
                if (folderOpen) {
                    folderOpen = false;
                    tvFolderArrow.setVisibility(View.INVISIBLE);
                    ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                    llFolderTop.setVisibility(View.GONE);
                    folderRcv.setVisibility(View.VISIBLE);
                } else {
                    folderOpen = true;
                    tvFolderArrow.setVisibility(View.VISIBLE);
                    ivFolderArrow.setBackgroundResource(R.drawable.iv_arrow_up_18);
                    llFolderTop.setVisibility(View.VISIBLE);
                    folderRcv.setVisibility(View.GONE);
                }
                break;
            case R.id.llFileArrow:
            case R.id.llFileTop:
                if (fileOpen) {
                    fileOpen = false;
                    tvFileArrow.setVisibility(View.INVISIBLE);
                    ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_down_18);
                    llFileTop.setVisibility(View.GONE);
                    fileRcv.setVisibility(View.VISIBLE);
                } else {
                    fileOpen = true;
                    tvFileArrow.setVisibility(View.VISIBLE);
                    ivFileArrow.setBackgroundResource(R.drawable.iv_arrow_up_18);
                    llFileTop.setVisibility(View.VISIBLE);
                    fileRcv.setVisibility(View.GONE);
                }
                break;

        }
    }
}
